<?php


namespace app\api\services;


use app\admin\model\HtnsOrderRefund;
use app\admin\model\HtnsOrderStatus;

/**
 * Class OrderService
 * @package app\api\services
 * @desc 订单服务类
 */
class OrderService
{
    use ApiTrait;

    /**
     * @desc 订单日志整合
     * @param int $id 售后订单id
     */
    public function orderLogMerge($id)
    {
        $ret = [];$rest = [];
        $where[] = ['oid','=',$id];
        $htnsOrderStatus = HtnsOrderStatus::where($where)->select()->toArray();
        if($htnsOrderStatus){
            /*"订单日记优化一下，需要的信息：创建
订单时间，支付订单时间，报关时间，报关状态，发货时间，退款时间，退款状态（成功，拒绝。失败）清关时间，确认收货时间。订单完成"
*/
            foreach ($htnsOrderStatus as $v) {
                $v['change_time'] = empty($v['change_time']) ? '' : date('Y-m-d H:i:s',$v['change_time']);
                if($v['change_type'] == 'cache_key_create_order'){
//                    $v['change_message'] = '创建订单';
                    $rest[0] = $v;
                }elseif ($v['change_type'] == 'pay_success'){
//                    $v['change_message'] = '支付订单';
                    $rest[1] = $v;
                }elseif ($v['change_type'] == 'tlpay_query_baoguan'){
                    $rest[2] = $v;
                }elseif ($v['change_type'] == 'delivery_goods'){
                    $rest[3] = $v;
                }elseif ($v['change_type'] == 'apply_refund'){
                    $rest[4] = $v;
                }elseif ($v['change_type'] == 'refund_price'){
                    $v['change_message'] .= '-退款成功';
                    $rest[5] = $v;
                }elseif ($v['change_type'] == 'tlpay_qingguan'){
                    $rest[6] = $v;
                }elseif ($v['change_type'] == 'user_take_delivery' || $v['change_type'] == 'take_delivery'){
                    $rest[7] = $v;
                }elseif ($v['change_type'] == 'order_complete'){
                    $rest[8] = $v;
                }
                // 是否拒绝退款
                $whereR['store_order_id'] = $v['oid'];
                $refund = HtnsOrderRefund::where($whereR)->order('id desc')->find();
                if($refund && $refund['refund_type'] == 3){
                    $rest[5] = [
                        'oid' => $refund['store_order_id'],
                        'change_type' => 'refund_no',
                        'change_message' => '拒绝退款-原因:'.$refund['refuse_reason'],
                        'change_time' => empty($refund['refunded_time']) ? '' : date('Y-m-d H:i:s',$refund['refunded_time']),
                    ];
                }
            }
            if($rest){
                $ret =  array_reverse($rest);
            }
        }
        return $ret;
    }
}